import AppConfig from '@/config';
import { useErrorHandler } from '@/utils/errorHandler';
import { computed, reactive, ref } from 'vue';
import { useLoading } from './useLoading';

/**
 * 数据表格管理 Composable
 * @param {Function} fetchFn - 获取数据的函数
 * @param {Object} options - 配置选项
 * @returns {Object} 表格管理对象
 */
export function useDataTable(fetchFn, options = {}) {
    const {
        immediate = true,
        pageSize = AppConfig.ui.pageSize,
        sortField = null,
        sortOrder = 1, // 1: 升序, -1: 降序
        filters = {},
        globalFilterFields = []
    } = options;

    const errorHandler = useErrorHandler();
    const { isLoading, withLoading } = useLoading();

    // 数据状态
    const items = ref([]);
    const selectedItems = ref([]);
    const totalRecords = ref(0);

    // 分页状态
    const pagination = reactive({
        page: 0, // PrimeVue从0开始
        rows: pageSize,
        first: 0
    });

    // 排序状态
    const sorting = reactive({
        sortField: sortField,
        sortOrder: sortOrder
    });

    // 筛选状态
    const filtering = reactive({
        filters: { ...filters },
        globalFilter: ''
    });

    /**
     * 加载数据
     * @param {Object} params - 查询参数
     */
    const loadData = withLoading(async (params = {}) => {
        try {
            const queryParams = {
                page: pagination.page + 1, // 转换为1开始的页码
                pageSize: pagination.rows,
                sortField: sorting.sortField,
                sortOrder: sorting.sortOrder,
                ...filtering.filters,
                globalFilter: filtering.globalFilter,
                ...params
            };

            const result = await fetchFn(queryParams);

            if (result && result.Data) {
                items.value = Array.isArray(result.Data) ? result.Data : result.Data.items || [];
                totalRecords.value = result.Total || result.Data.total || items.value.length;
            } else {
                items.value = [];
                totalRecords.value = 0;
            }
        } catch (error) {
            errorHandler.handleNetworkError(error, '加载数据');
            items.value = [];
            totalRecords.value = 0;
        }
    });

    /**
     * 处理分页变化
     * @param {Object} event - 分页事件
     */
    const onPageChange = (event) => {
        pagination.page = event.page;
        pagination.rows = event.rows;
        pagination.first = event.first;
        loadData();
    };

    /**
     * 处理排序变化
     * @param {Object} event - 排序事件
     */
    const onSortChange = (event) => {
        sorting.sortField = event.sortField;
        sorting.sortOrder = event.sortOrder;
        loadData();
    };

    /**
     * 处理筛选变化
     * @param {Object} event - 筛选事件
     */
    const onFilterChange = (event) => {
        filtering.filters = { ...event.filters };
        // 重置到第一页
        pagination.page = 0;
        pagination.first = 0;
        loadData();
    };

    /**
     * 处理全局搜索
     * @param {string} value - 搜索值
     */
    const onGlobalFilter = (value) => {
        filtering.globalFilter = value;
        // 重置到第一页
        pagination.page = 0;
        pagination.first = 0;
        loadData();
    };

    /**
     * 刷新数据
     */
    const refresh = () => {
        loadData();
    };

    /**
     * 重置筛选
     */
    const resetFilters = () => {
        filtering.filters = { ...filters };
        filtering.globalFilter = '';
        pagination.page = 0;
        pagination.first = 0;
        loadData();
    };

    /**
     * 导出数据
     * @param {Object} dt - DataTable实例引用
     * @param {string} filename - 文件名
     */
    const exportCSV = (dt, filename = 'export') => {
        if (dt.value) {
            dt.value.exportCSV({
                selectionOnly: false,
                filename: `${filename}_${new Date().toISOString().split('T')[0]}.csv`
            });
        } else {
            errorHandler.showError('无法导出数据，表格实例未找到');
        }
    };

    /**
     * 选择所有项
     * @param {Object} event - 选择事件
     */
    const onSelectAllChange = (event) => {
        selectedItems.value = event.checked ? [...items.value] : [];
    };

    /**
     * 批量删除选中项
     * @param {Function} deleteFn - 删除函数
     */
    const bulkDelete = withLoading(async (deleteFn) => {
        if (selectedItems.value.length === 0) {
            errorHandler.showWarning('请先选择要删除的项目');
            return;
        }

        try {
            await deleteFn(selectedItems.value);
            selectedItems.value = [];
            await loadData();
            errorHandler.showSuccess(`成功删除 ${selectedItems.value.length} 个项目`);
        } catch (error) {
            errorHandler.handleNetworkError(error, '批量删除');
        }
    });

    // 计算属性
    const hasSelection = computed(() => selectedItems.value.length > 0);
    const totalPages = computed(() => Math.ceil(totalRecords.value / pagination.rows));
    const currentPageInfo = computed(() => {
        const start = pagination.first + 1;
        const end = Math.min(pagination.first + pagination.rows, totalRecords.value);
        return { start, end, total: totalRecords.value };
    });

    // 自动加载初始数据
    if (immediate) {
        loadData();
    }

    return {
        // 数据状态
        items: computed(() => items.value),
        selectedItems: computed(() => selectedItems.value),
        totalRecords: computed(() => totalRecords.value),
        isLoading,

        // 分页状态
        pagination: computed(() => pagination),
        totalPages,
        currentPageInfo,

        // 排序状态
        sorting: computed(() => sorting),

        // 筛选状态
        filtering: computed(() => filtering),

        // 计算属性
        hasSelection,

        // 方法
        loadData,
        refresh,
        onPageChange,
        onSortChange,
        onFilterChange,
        onGlobalFilter,
        resetFilters,
        exportCSV,
        onSelectAllChange,
        bulkDelete
    };
}

/**
 * 简单列表管理 Composable (不分页)
 * @param {Function} fetchFn - 获取数据的函数
 * @param {Object} options - 配置选项
 * @returns {Object} 列表管理对象
 */
export function useSimpleList(fetchFn, options = {}) {
    const {
        immediate = true,
        autoRefresh = false,
        refreshInterval = 30000
    } = options;

    const errorHandler = useErrorHandler();
    const { isLoading, withLoading } = useLoading();

    const items = ref([]);
    const selectedItems = ref([]);
    const refreshTimer = ref(null);

    /**
     * 加载数据
     */
    const loadData = withLoading(async (params = {}) => {
        try {
            const result = await fetchFn(params);
            items.value = Array.isArray(result) ? result : result.Data || [];
        } catch (error) {
            errorHandler.handleNetworkError(error, '加载数据');
            items.value = [];
        }
    });

    /**
     * 刷新数据
     */
    const refresh = () => {
        loadData();
    };

    /**
     * 开始自动刷新
     */
    const startAutoRefresh = () => {
        if (autoRefresh && !refreshTimer.value) {
            refreshTimer.value = setInterval(refresh, refreshInterval);
        }
    };

    /**
     * 停止自动刷新
     */
    const stopAutoRefresh = () => {
        if (refreshTimer.value) {
            clearInterval(refreshTimer.value);
            refreshTimer.value = null;
        }
    };

    // 自动加载初始数据
    if (immediate) {
        loadData().then(() => {
            if (autoRefresh) {
                startAutoRefresh();
            }
        });
    }

    // 清理定时器
    onBeforeUnmount(() => {
        stopAutoRefresh();
    });

    return {
        items: computed(() => items.value),
        selectedItems: computed(() => selectedItems.value),
        isLoading,
        loadData,
        refresh,
        startAutoRefresh,
        stopAutoRefresh
    };
}
